package com.raven.craft.code.generator.mysql.mybatis;

import com.raven.craft.code.generator.IGenerator;
import com.raven.craft.code.generator.common.file.HbsFile;
import com.raven.craft.code.generator.common.file.metadata.FileMetadata;
import com.raven.craft.code.generator.common.file.metadata.JavaFileMetadata;
import com.raven.craft.code.generator.config.MysqlContext;
import com.raven.craft.code.generator.mysql.repo.entity.Table;
import lombok.extern.slf4j.Slf4j;

/**
 * @author raven
 * @date 2020/08/25
 **/
@Slf4j
public class MybatisGenerator implements IGenerator {

    private final MysqlContext context;
    private final MyBatisProperties properties;

    public MybatisGenerator(MysqlContext context, MyBatisProperties properties) {
        this.context = context;
        this.properties = properties;
    }

    private static HbsFile createEntityFile(MyBatisProperties properties, Table table) {
        EntityVo vo = new EntityVo(properties, table);
        FileMetadata metadata = new JavaFileMetadata(vo.getName(), properties.getTargetDir(), properties.getEntityPackage());
        return new HbsFile(metadata, properties.getEntityTemplatePath(), vo);
    }

    private static HbsFile createMapperFile(MyBatisProperties properties, Table table) {
        MapperVo vo = new MapperVo(properties, table);
        FileMetadata metadata = new JavaFileMetadata(vo.getName(), properties.getTargetDir(), properties.getMapperPackage());
        return new HbsFile(metadata, properties.getMapperTemplatePath(), vo);
    }

    private static HbsFile createServiceFile(MyBatisProperties properties, Table table) {
        ServiceVo vo = new ServiceVo(properties, table);
        FileMetadata metadata = new JavaFileMetadata(vo.getName(), properties.getTargetDir(), properties.getServicePackage());
        return new HbsFile(metadata, properties.getServiceTemplatePath(), vo);
    }

    private static HbsFile createVoFile(MyBatisProperties properties, Table table) {
        VoVo vo = new VoVo(properties, table);
        FileMetadata metadata = new JavaFileMetadata(vo.getName(), properties.getTargetDir(), properties.getVoPackage());
        return new HbsFile(metadata, properties.getVoTemplatePath(), vo);
    }

    @Override
    public void generate() {
        log.info("begin to generate mybatis file");
        context.getTables().forEach(table -> {
            createEntityFile(properties, table).output();
            createMapperFile(properties, table).output();
            createServiceFile(properties, table).output();
            createVoFile(properties, table).output();
        });
    }
}
